package com.qike.duola.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qike.duola.domain.*;
import com.qike.duola.dto.ProjectAddDto;
import com.qike.duola.dto.ProjectEditDto;
import com.qike.duola.dto.ProjectListDto;
import com.qike.duola.enums.*;
import com.qike.duola.mapper.*;
import com.qike.duola.service.ApprovalService;
import com.qike.duola.service.DuolaPlanService;
import com.qike.duola.service.DuolaProjectService;
import com.qike.duola.utils.TimeTool;
import com.qike.duola.vo.*;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @Author: Eric.zhou
 * @Date: 2020/9/1 16:45
 */
@Service
public class DuolaProjectServiceImpl implements DuolaProjectService {

    private static final Logger logger = LoggerFactory.getLogger(DuolaProjectServiceImpl.class);

    @Autowired
    private DuolaProjectMapper duolaProjectMapper;
    @Autowired
    private DuolaExamineMapper duolaExamineMapper;
    @Autowired
    private DuolaCustomerMapper duolaCustomerMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ApprovalService approvalService;

    @Autowired
    private DuolaPlanMapper duolaPlanMapper;
    @Autowired
    private DuolaTransOrderMapper duolaTransOrderMapper;

    /**
     * t添加工程
     *
     * @param projectAddDto
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void projectAdd(ProjectAddDto projectAddDto) throws Exception {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"添加工程"+ JSON.toJSON(projectAddDto));
        approvalService.findProcess(ApprovalOrderTypeEnums.PROJECT.getEcode());
        //添加工程
        DuolaProject duolaProject = new DuolaProject();
        duolaProject.setAddTime(LocalDateTime.now());
        duolaProject.setAddUid(userId);
        duolaProject.setCustomerId(projectAddDto.getCustomerUId());
        duolaProject.setContractName(projectAddDto.getContractName());
        duolaProject.setContractPhone(projectAddDto.getContractPhone());
        duolaProject.setProjectAddress(projectAddDto.getAddress());
        duolaProject.setSaleUid(projectAddDto.getSaleUId());
        duolaProject.setStartTime(new Date(projectAddDto.getStartTime()).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime());
        duolaProject.setEndTime(new Date(projectAddDto.getEndTime()).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime());
        duolaProject.setProjectNum(projectAddDto.getProjectNum());
        duolaProject.setRemark(projectAddDto.getRemark());
        duolaProject.setProjectAddress(projectAddDto.getAddress());
        duolaProject.setLatitude(projectAddDto.getLatitude());
        duolaProject.setLongitude(projectAddDto.getLongitude());
        duolaProject.setDistance(projectAddDto.getDistance());
        duolaProject.setStatus(StatusEnums.NO.getEcode());
        duolaProject.setProjectName(projectAddDto.getProjectName());
        duolaProject.setExamineStatus(ExamineEnums.EXAMINE_ING.getEcode());
        duolaProjectMapper.insertSelective(duolaProject);
        String processId = "";
        //todo 发起审批
        try {
            approvalService.startApproval(userId,duolaProject.getId(), ApprovalOrderTypeEnums.PROJECT.getEcode());
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 工程编辑
     *
     * @param projectEditDto
     */
    @Override
    public void projectEdit(ProjectEditDto projectEditDto) throws Exception {
        Integer id = projectEditDto.getId();
        DuolaProject duolaProject = duolaProjectMapper.selectByPrimaryKey(id);
        if (duolaProject==null){
            throw new Exception(ErrorEnums.ERROR_DATA.getEmsg());
        }
        if (!duolaProject.getExamineStatus().equals(ExamineEnums.EXAMINE_REFUSE.getEcode())){
            throw new Exception(ErrorEnums.ERROR_UPDATE.getEmsg());
        }
        approvalService.findProcess(ApprovalOrderTypeEnums.PROJECT.getEcode());
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"编辑工程"+ JSON.toJSON(projectEditDto));
        //添加工程
        duolaProject.setAddTime(LocalDateTime.now());
        duolaProject.setAddUid(userId);
        duolaProject.setCustomerId(projectEditDto.getCustomerUId());
        duolaProject.setContractName(projectEditDto.getContractName());
        duolaProject.setContractPhone(projectEditDto.getContractPhone());
        duolaProject.setProjectAddress(projectEditDto.getAddress());
        duolaProject.setSaleUid(projectEditDto.getSaleUId());
        duolaProject.setStartTime(new Date(projectEditDto.getStartTime()).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime());
        duolaProject.setEndTime(new Date(projectEditDto.getEndTime()).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime());
        duolaProject.setProjectNum(projectEditDto.getProjectNum());
        duolaProject.setRemark(projectEditDto.getRemark());
        duolaProject.setProjectAddress(projectEditDto.getAddress());
        duolaProject.setLatitude(projectEditDto.getLatitude());
        duolaProject.setLongitude(projectEditDto.getLongitude());
        duolaProject.setDistance(projectEditDto.getDistance());
        duolaProject.setStatus(StatusEnums.NO.getEcode());
        duolaProject.setProjectName(projectEditDto.getProjectName());
        duolaProject.setExamineStatus(ExamineEnums.EXAMINE_ING.getEcode());
        duolaProjectMapper.updateByPrimaryKeySelective(duolaProject);
        //todo 发起审批
        approvalService.startApproval(userId,duolaProject.getId(), ApprovalOrderTypeEnums.PROJECT.getEcode());
    }

    /**
     * 工程列表
     *
     * @param projectListDto
     * @return
     */
    @Override
    public ProjectListVo projectList(ProjectListDto projectListDto) {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"工程列表"+ JSON.toJSON(projectListDto));
        Map<Integer,String> customerNameMap = new HashMap<>();
        List<DuolaCustomer> duolaCustomers = duolaCustomerMapper.selectByExample(new DuolaCustomerExample());
        for (DuolaCustomer duolaCustomer : duolaCustomers) {
            customerNameMap.put(duolaCustomer.getId(),duolaCustomer.getCustomerName());
        }
        ProjectListVo vo = new ProjectListVo();
        List<ProjectList> list = new ArrayList<>();
        DuolaProjectExample projectExample = new DuolaProjectExample();
        DuolaProjectExample.Criteria criteria = projectExample.createCriteria();
        if (projectListDto.getCustomerId()!=null){
            criteria.andCustomerIdEqualTo(projectListDto.getCustomerId());
        }
        if (!StringUtils.isEmpty(projectListDto.getContractName())){
            criteria.andContractNameEqualTo(projectListDto.getContractName());
        }
        if (!StringUtils.isEmpty(projectListDto.getContractName())){
            criteria.andContractNameEqualTo(projectListDto.getContractName());
        }
        if (projectListDto.getProjectName()!=null){
            criteria.andProjectNameLike(projectListDto.getProjectName());
        }
        if (projectListDto.getContractPhone()!=null){
            criteria.andContractPhoneEqualTo(projectListDto.getContractPhone());
        }
        projectExample.setOrderByClause("add_time desc");
        Page page = PageHelper.startPage(projectListDto.getStartPage(), projectListDto.getPageSize());
        List<DuolaProject> duolaProjects = duolaProjectMapper.selectByExample(projectExample);
        for (DuolaProject duolaProject : duolaProjects) {
            ProjectList projectList = new ProjectList();
            projectList.setAddress(duolaProject.getProjectAddress());
            projectList.setRemark(duolaProject.getRemark());
            projectList.setName(duolaProject.getContractName());
            projectList.setProjectNum(duolaProject.getProjectNum());
            projectList.setDistance(duolaProject.getDistance());
            projectList.setPhone(duolaProject.getContractPhone());
            projectList.setCustomerName(customerNameMap.get(duolaProject.getCustomerId()));
            projectList.setProjectName(duolaProject.getProjectName());
            projectList.setAddTime(duolaProject.getAddTime().toString());
            projectList.setExaminStr(ExamineEnums.statOf(duolaProject.getExamineStatus()).getEmsg());
            projectList.setId(duolaProject.getId());
            list.add(projectList);
        }
        vo.setList(list);
        vo.setTotal(page.getTotal());
        return vo;
    }

    /**
     * 工程详情
     *
     * @param id
     * @return
     */
    @Override
    public ProjectInfoVo projectInfo(Integer id) throws Exception {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"工程详情"+ JSON.toJSON(id));
        DuolaProject duolaProject = duolaProjectMapper.selectByPrimaryKey(id);
        if (duolaProject==null){
            throw new Exception(ErrorEnums.ERROR_DATA.getEmsg());
        }
        ProjectInfoVo vo = new ProjectInfoVo();
        vo.setAddress(duolaProject.getProjectAddress());
        vo.setContractName(duolaProject.getContractName());
        vo.setContractPhone(duolaProject.getContractPhone());
        vo.setCustomerName(duolaCustomerMapper.selectByPrimaryKey(duolaProject.getCustomerId()).getCustomerName());
        vo.setDistance(duolaProject.getDistance());
        vo.setEndTime(duolaProject.getEndTime().toString());
        vo.setStartTime(duolaProject.getStartTime().toString());
        vo.setSaleUId(duolaProject.getSaleUid());
        vo.setSaleName(sysUserMapper.selectByPrimaryKey(duolaProject.getSaleUid()).getNickname());
        vo.setRemark(duolaProject.getRemark());
        vo.setProjectNum(duolaProject.getProjectNum());
        vo.setProjectName(duolaProject.getProjectName());
        vo.setLatitude(duolaProject.getLatitude());
        vo.setLongitude(duolaProject.getLongitude());
        vo.setCustomerUId(duolaProject.getCustomerId());
        vo.setSaleUId(duolaProject.getSaleUid());
        return vo;
    }

    /**
     * 删除工程
     *
     * @param id
     */
    @Override
    public void projectDel(Integer id) throws Exception {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"删除工程"+ JSON.toJSON(id));
        DuolaProject duolaProject = duolaProjectMapper.selectByPrimaryKey(id);
        if (duolaProject==null){
            throw new Exception(ErrorEnums.ERROR_DATA.getEmsg());
        }
        if (duolaProject.getExamineStatus().equals(ExamineEnums.EXAMINE_REFUSE.getEcode())){
            duolaProject.setStatus(StatusEnums.YES.getEcode());
            duolaProject.setUpdateUid(userId);
            duolaProject.setUpdateTime(LocalDateTime.now());
            duolaProjectMapper.updateByPrimaryKey(duolaProject);
        }else {
            throw new Exception(ErrorEnums.COURSE_NOT_START.getEmsg());
        }
    }

    /**
     * 获取某个客户下所有已审批的合同下工程列表
     *
     * @param uid
     * @return
     */
    @Override
    public List<DuolaProject> GetProjectListByUid(Integer uid) {
//        duola
        DuolaProjectExample example = new DuolaProjectExample();
        example.createCriteria().andCustomerIdEqualTo(uid).andExamineStatusEqualTo(ExamineEnums.EXAMINE_SUCCESS.getEcode());
        List<DuolaProject> duolaProjects = duolaProjectMapper.selectByExample(example);
        return duolaProjects;
    }

    /**
     * 工程名称下拉
     *
     * @param name
     * @return
     */
    @Override
    public List<EnumList> projectPullList(String name) {
        List<EnumList> lists = new ArrayList<>();
        DuolaProjectExample example = new DuolaProjectExample();
        if (!StringUtils.isEmpty(name)){
            example.createCriteria().andProjectNameLike(name);
        }
        List<DuolaProject> duolaProjects = duolaProjectMapper.selectByExample(example);
        for (DuolaProject duolaCustomer : duolaProjects) {
            EnumList enumList = new EnumList();
            enumList.setKey(duolaCustomer.getId());
            enumList.setValue(duolaCustomer.getProjectName());
            lists.add(enumList);
        }
        return lists;
    }

    /**
     * 退料转料工程名称下拉
     *
     * @param name
     * @return
     */
    @Override
    public List<EnumList> ReTurnProjectPullList(String name,Integer transId) {
        List<EnumList> voList = new ArrayList<>();
        DuolaTransOrder duolaTransOrder = duolaTransOrderMapper.selectByPrimaryKey(transId);
        Integer planId = duolaTransOrder.getPlanId();
        DuolaPlan duolaPlan = duolaPlanMapper.selectByPrimaryKey(planId);
        LocalDateTime pouringTime = duolaPlan.getPouringTime();
        LocalDateTime startTime = TimeTool.getDayBeginLocalDateTime(pouringTime.toLocalDate());
        LocalDateTime endTime = TimeTool.getDayEndLocalDateTime(pouringTime.toLocalDate());
        DuolaPlanExample example = new DuolaPlanExample();
        example.createCriteria().andPouringTimeBetween(startTime,endTime).andStatusEqualTo(StatusEnums.NO.getEcode()).andOrderStatusEqualTo(PlanOrderStatusEnums.DRIVING.getEcode());
        List<DuolaPlan> duolaPlans = duolaPlanMapper.selectByExample(example);
        List<Integer> planProjectIds = new ArrayList<>();
        for (DuolaPlan plan : duolaPlans) {
            planProjectIds.add(plan.getProjectId());
        }
        if (planProjectIds.size()<=0){
            return  voList;
        }
        DuolaProjectExample projectExample = new DuolaProjectExample();
        DuolaProjectExample.Criteria criteria = projectExample.createCriteria().andIdIn(planProjectIds);
        if (!StringUtils.isEmpty(name)){
            criteria.andProjectNameLike(name);
        }
        List<DuolaProject> duolaProjects = duolaProjectMapper.selectByExample(projectExample);
        for (DuolaProject duolaProject : duolaProjects) {
            EnumList list = new EnumList();
            list.setKey(duolaProject.getId());
            list.setValue(duolaProject.getProjectName());
            voList.add(list);
        }
        return voList;
    }

    /**
     * 通过客户id获取已审批的工程
     *
     * @param name
     * @param customerId
     * @return
     */
    @Override
    public List<ProjectPullListByCustomerIdVo> projectPullListByCustomerId(String name, Integer customerId) {
        DuolaProjectExample example = new DuolaProjectExample();
        List<ProjectPullListByCustomerIdVo> list = new ArrayList<>();
        DuolaProjectExample.Criteria criteria = example.createCriteria().andExamineStatusEqualTo(ExamineEnums.EXAMINE_SUCCESS.getEcode()).andStatusEqualTo(StatusEnums.NO.getEcode());
        if (customerId!=null){
            criteria.andCustomerIdEqualTo(customerId);
        }
        if (!StringUtils.isEmpty(name)){
            criteria.andProjectNameLike(name);
        }
        Map<Long,String> userMap = new HashMap<>();
        List<SysUser> sysUsers = sysUserMapper.selectByExample(new SysUserExample());
        for (SysUser sysUser : sysUsers) {
            userMap.put(sysUser.getId(),sysUser.getNickname());
        }
        List<DuolaProject> duolaProjects = duolaProjectMapper.selectByExample(example);
        for (DuolaProject duolaProject : duolaProjects) {
            ProjectPullListByCustomerIdVo vo = new ProjectPullListByCustomerIdVo();
            vo.setId(duolaProject.getId());
            vo.setName(duolaProject.getProjectName());
            vo.setSaleName(userMap.get(duolaProject.getSaleUid()));
            vo.setSaleId(duolaProject.getSaleUid());
            list.add(vo);
        }
        return list;
    }
}
